#include "stdafx.h"
#include "TreeConfig.h"
#include "Resource.h"
#include "DataSeting.h"


void CTreeConfig::OnCreate(CTreeCtrl& tree)
{
    m_pIml = new CImageList();
    m_pIml->Create(16, 16, ILC_MASK|ILC_COLOR32, 4, 4);
    HINSTANCE hModule = ::AfxGetResourceHandle();
    UINT nIDIcons[] = {IDI_ICON_Set,IDI_ICON_Accept,IDI_ICON_Delete,0};
    for (int i=0; nIDIcons[i]!=0; ++i)
    {
        HICON hIcon = LoadIcon(hModule,MAKEINTRESOURCE(nIDIcons[i]));
        m_pIml->Add(hIcon);
    }
    ///tree.SetImageList(m_pIml, TVSIL_NORMAL);
}

void CTreeConfig::Show(CTreeCtrl& tree)
{
    Recursion(tree, NULL, mstrCur);
}

void CTreeConfig::Recursion(CTreeCtrl& tree, HTREEITEM hCur, CString str)
{
    WIN32_FIND_DATA wFD;
    HANDLE hFind = ::FindFirstFile(str+_T("\\*.*"), &wFD);
    if (hFind==INVALID_HANDLE_VALUE) return;

    do
    {
        BOOL bIsDir = (wFD.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)>0;

        if (bIsDir && wFD.cFileName[0]=='.')
            continue;
        if (bIsDir)
        {
            HTREEITEM hDir;
            hDir = tree.InsertItem(wFD.cFileName, hCur, TVI_LAST);
            Recursion(tree, hDir, str+_T("\\")+wFD.cFileName);
        }
        else
        {
            HTREEITEM hSelf = tree.InsertItem(wFD.cFileName, hCur, TVI_LAST);;
            CallBack(tree, hSelf, str+_T("\\")+wFD.cFileName);
            
        }

    }while(FindNextFile(hFind, &wFD));
    FindClose(hFind);

}

void CTreeConfig::CallBack(CTreeCtrl& tree, HTREEITEM hSelf, CString str)
{
    static sEdit sOO;
    static TCHAR _buf[1024];
    memset(_buf,0, 1024);

    DWORD dwCount, dw;
    HANDLE hFile = ::CreateFile(str,  GENERIC_READ, FILE_SHARE_READ , NULL, OPEN_EXISTING, NULL, NULL); 
	if (hFile==INVALID_HANDLE_VALUE ) return;

	::SetFilePointer(hFile, 0, 0, FILE_BEGIN);
    dwCount = ::GetFileSize(hFile, 0);
    ReadFile(hFile, _buf, dwCount, &dw, NULL);

    //CStdioFile oFile(str, CFile::modeRead);
    //int iLen = (int) oFile.GetLength();
    //oFile.Read(_buf, dw);
    if (_buf[0]==0xfeff)
    {
        CString tmp(_buf+1);
        Data().AddItem(hSelf, tmp);
    }
    else
    {
        CString tmp(_buf);
        Data().AddItem(hSelf, tmp);
    }

    //tree.SetItemImage(hSelf, 1, 1);
    //oFile.Close();
    CloseHandle(hFile);

}